package br.com.halyson.pontoeletronico;

import br.com.halyson.pontoeletronico.adapter.MenuListAdapter;
import br.com.halyson.pontoeletronico.adapter.ViewPagerAdapter;
import br.com.halyson.pontoeletronico.view.CargaHorariaFragment;
import br.com.halyson.pontoeletronico.view.PontoActivity;
import br.com.halyson.pontoeletronico.view.RemuneracaoFragment;
import br.com.halyson.pontoeletronico.view.SobreActivity;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.view.MenuItem;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;

public class MainActivity extends SherlockFragmentActivity
{
    
    private DrawerLayout drawerLayout;
    
    private ListView drawerList;
    
    private ActionBarDrawerToggle drawerToggle;
    
    private MenuListAdapter menuAdapter;
    
    private Tab tabAbas;
    
    private ActionBar actionBar;
    
    private ViewPager viewPager;
    
    private String[] title;
    
    private String[] subtitle;
    
    private int[] icon;
    
    private boolean flagTab = false;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drawer_main);
        
        title = new String[] { "Backup", "Carga Horária", "Remuneração", "Relatório", "Feriados", "Sobre" };
        
        subtitle =
            new String[] { "Salvar Base de Dados", "Configurar Meta Diária", "Configurar Valor/Hora", "Exportar Registros",
                    "Configurar Dispensas", "Detalhes do aplicativo" };
        
        icon =
            new int[] { R.drawable.backup, R.drawable.clock, R.drawable.money, R.drawable.archive, R.drawable.calender,
                    R.drawable.about };
        
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        
        drawerList = (ListView) findViewById(R.id.left_drawer);
        
        drawerLayout.setDrawerShadow(R.drawable.shadow, GravityCompat.START);
        
        menuAdapter = new MenuListAdapter(this, title, subtitle, icon);
        
        drawerList.setAdapter(menuAdapter);
        
        drawerList.setOnItemClickListener(new DrawerItemClickListener());
        
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        
        drawerToggle =
            new ActionBarDrawerToggle(this, drawerLayout, R.drawable.drawer, R.string.drawer_close, R.string.drawer_close)
            {
                public void onDrawerClosed(View view)
                {
                    super.onDrawerClosed(view);
                }
                
                public void onDrawerOpened(View drawerView)
                {
                    super.onDrawerOpened(drawerView);
                }
            };
        
        drawerLayout.setDrawerListener(drawerToggle);
        
        if (savedInstanceState == null)
        {
            selectItem(0);
        }
        
        // Obtem uma referência a Actionbar e seta o modo de navegação
        actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        
        // Obtem uma referência com ViewPager do Layout
        viewPager = (ViewPager) findViewById(R.id.pager);
        
        // Obtem uma referência ao FragmentManager
        FragmentManager fragmentManager = getSupportFragmentManager();
        
        // Captura ViewPager para movimentos swipe
        ViewPager.SimpleOnPageChangeListener ViewPagerListener = new ViewPager.SimpleOnPageChangeListener()
        {
            @Override
            public void onPageSelected(int position)
            {
                super.onPageSelected(position);
                // Encontra a posição da navegação nas tabs
                actionBar.setSelectedNavigationItem(position);
            }
        };
        
        viewPager.setOnPageChangeListener(ViewPagerListener);
        
        // Objeto para adaptar as mudação de página na navegação swipe
        ViewPagerAdapter viewpageradapter = new ViewPagerAdapter(fragmentManager);
        
        // Seta a página atual para visuaização
        viewPager.setAdapter(viewpageradapter);
        
        // Escuta qual tab será seleciona para setar as informações
        ActionBar.TabListener tabListener = new ActionBar.TabListener()
        {
            @Override
            public void onTabUnselected(Tab tab, FragmentTransaction ft)
            {
            }
            
            @Override
            public void onTabSelected(Tab tab, FragmentTransaction ft)
            {
                viewPager.setCurrentItem(tab.getPosition());
            }
            
            @Override
            public void onTabReselected(Tab tab, FragmentTransaction ft)
            {
            }
        };
        
        // Adiciona tab's na action bar
        tabAbas = actionBar.newTab().setText("Ponto").setTabListener(tabListener);
        actionBar.addTab(tabAbas);
        
        tabAbas = actionBar.newTab().setText("Registros").setTabListener(tabListener);
        actionBar.addTab(tabAbas);
        
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if (item.getItemId() == android.R.id.home)
        {
            if (drawerLayout.isDrawerOpen(drawerList))
            {
                if (flagTab)
                {
                    drawerLayout.closeDrawer(drawerList);
                }
                else
                {
                    actionBar.setNavigationMode(actionBar.NAVIGATION_MODE_TABS);
                    drawerLayout.closeDrawer(drawerList);
                }
            }
            else
            {
                actionBar.setNavigationMode(actionBar.NAVIGATION_MODE_STANDARD);
                drawerLayout.openDrawer(drawerList);
            }
        }
        return super.onOptionsItemSelected(item);
    }
    
    private class DrawerItemClickListener implements ListView.OnItemClickListener
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            flagTab = true;
            actionBar.setNavigationMode(actionBar.NAVIGATION_MODE_STANDARD);
            drawerToggle.setDrawerIndicatorEnabled(false);
            selectItem(position);
        }
    }
    
    private void selectItem(int position)
    {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        switch (position)
        {
        case 0:
            ft.replace(R.id.content_frame, new PontoActivity());
            break;
        case 1:
            ft.replace(R.id.content_frame, new CargaHorariaFragment());
            break;
        case 2:
            ft.replace(R.id.content_frame, new RemuneracaoFragment());
            break;
        case 5:
            ft.replace(R.id.content_frame, new SobreActivity());
            break;
        }
        ft.commit();
        drawerList.setItemChecked(position, true);
        drawerLayout.closeDrawer(drawerList);
    }
    
    @Override
    protected void onPostCreate(Bundle savedInstanceState)
    {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }
    
}